<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Fapi extends CI_Controller {

    
    public function __construct()
    {
        $this->url=[];
        $this->sid=[];
        $this->logfile=APPPATH.'logs'.DIRECTORY_SEPARATOR."url.txt";
        $this->shopidlogfile=APPPATH.'logs'.DIRECTORY_SEPARATOR."shopid.txt";
        $this->getlog();
        parent::__construct();
    }
	
    
    public function revive()
    {
        $url=$_REQUEST["url"];
        $items=explode("\n",$url);
        $cc=0;
        if($items)
        {
            foreach($items as $item)
            {
                if(empty($item)) continue;
                $tmp=explode("/",$item);
                $tmp=explode(".html",array_pop($tmp));
                $id=$tmp[0];
                if(!in_array($id,$this->url))
                {
                    $cc++;
                    $this->url[]=$id;
                }
            }
        }
        if(count($this->url)>0)
        {
            $this->savelog();
        }
        $callback=$this->input->get("callbackparam");
        echo $callback.'('.json_encode([]).')';
        die();
    }

    public function revivesid()
    {
        $sid=$_REQUEST["sid"];       
        if(!in_array($sid,$this->sid))
        {
            $this->sid[]=$sid;
        }
        if(count($this->sid)>0)
        {
            $this->saveshopidlog();
        }
        $callback=$this->input->get("callbackparam");
        echo $callback.'('.json_encode([]).')';
        die();
    }

    public function showsid()
    {        
        foreach($this->sid as $i)
        {
            echo $i."<br/>";
        }
        die();
    }

    public function clearsid()
    {
        $this->sid=[];
        if(file_exists($this->shopidlogfile))
        {
            unlink($this->shopidlogfile);
        }
        die("clear ok");
    }

    public function clear()
    {
        $this->url=[];
        if(file_exists($this->logfile))
        {
            unlink($this->logfile);
        }
        die("clear ok");
    }

    public function show()
    {
        foreach($this->url as $i)
        {
            echo "https://www.aliexpress.com/item/".$i.".html<br/>";
        }
        die();
    }
    
    private function getlog()
    {
        if(file_exists($this->logfile))
        {
            $info=file_get_contents($this->logfile);
            $this->url=json_decode($info,true);
        }      

        if(file_exists($this->shopidlogfile))
        {
            $info=file_get_contents($this->shopidlogfile);
            $this->sid=json_decode($info,true);
        }  
        
    }

    private function saveshopidlog()
    {
        $allinfo=json_encode($this->sid);
        file_put_contents($this->shopidlogfile,$allinfo);
    }

    private function savelog()
    {
        $allinfo=json_encode($this->url);
        file_put_contents($this->logfile,$allinfo);
    }



}
